/*
 * ImportRouteShpFrame.java
 *
 * Created on June 17, 2007, 5:01 PM
 *
 * Copyright 2008 David D. Emory
 * 
 * This file is part of Five Points. See <http://www.fpdev.org> for
 * additional information regarding the project.
 * 
 * Five Points is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Five Points is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Five Points.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.fpdev.apps.admin.gui;

import org.fpdev.util.gui.GUIFactory;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
import javax.swing.AbstractButton;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.ListSelectionModel;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import org.fpdev.apps.admin.ACEvent;
import org.fpdev.apps.admin.AdminClient;
import org.fpdev.apps.admin.EventTypes;

/**
 *
 * @author demory
 */
public class ImportRouteShpFrame extends JFrame implements ActionListener {

  private AdminClient av_;
  private JList rteList_;
  private DefaultListModel rListModel_;
  private JScrollPane rScrollPane_;
  private JTable table_;
  private ListSelectionModel tableLSM_;
  private JScrollPane tScrollPane_;
  private JCheckBox autoShow_;
  private JTextField bufferRadius_;
  private JButton showBtn_,  resolveBtn_,  clearBtn_,  applyBtn_;
  private JToggleButton setStartBtn_,  setEndBtn_,  editLinksBtn_,  setPathBtn_;
  private HashSet<AbstractButton> btnSet_;
  private Map<String, List> rteLookup_;

  /** Creates a new instance of ImportRouteShpFrame */
  public ImportRouteShpFrame(AdminClient av, ACGUI gui) {
    super("Import Routes from Shapefile");
    av_ = av;

    rteLookup_ = new HashMap<String, List>();

    rListModel_ = new DefaultListModel();
    rteList_ = new JList(rListModel_);
    rteList_.setFont(GUIFactory.MAIN_FONT);
    rteList_.addListSelectionListener(new ListSelectionListener() {

      public void valueChanged(ListSelectionEvent e) {
        routeRowSelected();//selectedRow);
      }
    });
    rScrollPane_ = new JScrollPane(rteList_);
    rScrollPane_.setMinimumSize(new Dimension(60, 1));

    table_ = new JTable();
    table_.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    ListSelectionModel rowLSM = table_.getSelectionModel();
    rowLSM.addListSelectionListener(new ListSelectionListener() {

      public void valueChanged(ListSelectionEvent e) {
        if (e.getValueIsAdjusting()) {
          return;
        } //Ignore extra messages.
        tableLSM_ = (ListSelectionModel) e.getSource();
        if (!tableLSM_.isSelectionEmpty()) {
          int selectedRow = tableLSM_.getMinSelectionIndex();
          rowSelected(selectedRow);
        }
      }
    });

    tScrollPane_ = new JScrollPane(table_);

    JPanel mainRow = new JPanel();
    mainRow.setLayout(new BoxLayout(mainRow, BoxLayout.X_AXIS));
    mainRow.add(rScrollPane_);
    mainRow.add(Box.createHorizontalStrut(5));
    mainRow.add(tScrollPane_);

    autoShow_ = GUIFactory.newCheckBox("Auto-Show");
    bufferRadius_ = GUIFactory.newTextField("50", 5, 20);

    showBtn_ = GUIFactory.newButton("Show", 60, this);
    resolveBtn_ = GUIFactory.newButton("Resolve", 60, this);
    clearBtn_ = GUIFactory.newButton("Clear Current", 100, this);
    applyBtn_ = GUIFactory.newButton("Apply to Selected", 100, this);

    setStartBtn_ = GUIFactory.newToggleButton("Set Start", 70, this);
    setEndBtn_ = GUIFactory.newToggleButton("Set End", 70, this);
    editLinksBtn_ = GUIFactory.newToggleButton("Edit Links", 70, this);
    setPathBtn_ = GUIFactory.newToggleButton("Set Path", 70, this);

    btnSet_ = new HashSet<AbstractButton>();

    btnSet_.add(showBtn_);
    btnSet_.add(resolveBtn_);
    btnSet_.add(applyBtn_);
    btnSet_.add(setStartBtn_);
    btnSet_.add(setEndBtn_);
    btnSet_.add(editLinksBtn_);
    btnSet_.add(setPathBtn_);

    JPanel btnRow1 = new JPanel();
    btnRow1.setLayout(new BoxLayout(btnRow1, BoxLayout.X_AXIS));
    btnRow1.add(Box.createHorizontalGlue());
    btnRow1.add(showBtn_);
    btnRow1.add(autoShow_);
    btnRow1.add(Box.createHorizontalStrut(15));
    btnRow1.add(resolveBtn_);
    btnRow1.add(bufferRadius_);
    btnRow1.add(Box.createHorizontalGlue());

    JPanel btnRow2 = new JPanel();
    btnRow2.setLayout(new BoxLayout(btnRow2, BoxLayout.X_AXIS));
    btnRow2.add(Box.createHorizontalGlue());
    btnRow2.add(setStartBtn_);
    btnRow2.add(setEndBtn_);
    btnRow2.add(editLinksBtn_);
    btnRow2.add(setPathBtn_);
    btnRow2.add(Box.createHorizontalGlue());

    JPanel btnRow3 = new JPanel();
    btnRow3.setLayout(new BoxLayout(btnRow3, BoxLayout.X_AXIS));
    btnRow3.add(Box.createHorizontalGlue());
    btnRow3.add(clearBtn_);
    btnRow3.add(Box.createHorizontalStrut(5));
    btnRow3.add(applyBtn_);
    btnRow3.add(Box.createHorizontalGlue());


    JPanel mainPanel = new JPanel();
    mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
    mainPanel.setBorder(new EmptyBorder(3, 3, 3, 3));
    mainPanel.add(mainRow);
    mainPanel.add(Box.createVerticalStrut(5));
    mainPanel.add(btnRow1);
    mainPanel.add(Box.createVerticalStrut(4));
    mainPanel.add(btnRow2);
    mainPanel.add(Box.createVerticalStrut(4));
    mainPanel.add(btnRow3);

    this.getContentPane().add(mainPanel);

    pack();
    setSize(new Dimension(320, 240));
    this.setAlwaysOnTop(true);

    this.setLocation((gui.getWidth() / 2) - getWidth() / 2 + gui.getX(),
            (gui.getHeight() / 2) - getHeight() / 2 + gui.getY());

  }

  public void actionPerformed(ActionEvent e) {
    if (e.getSource() == showBtn_ || e.getSource() == resolveBtn_) {
      int r = table_.getSelectedRow();
      if (r < 0) {
        av_.msg("No item selected");
        return;
      }
      //r = table_.getRowSorter().convertRowIndexToModel(r);
      ACEvent ave = null;

      if (e.getSource() == showBtn_) {
        ave = new ACEvent(EventTypes.RTESHP_SHOW_ITEM);
      }
      if (e.getSource() == resolveBtn_) {
        ave = new ACEvent(EventTypes.RTESHP_RESOLVE_ITEM);
        ave.setProperty("radius", new Double(bufferRadius_.getText()).doubleValue());
      }

      //String val = table_.getModel().getValueAt(r,0)+"_"+table_.getModel().getValueAt(r,1)+"_"+table_.getModel().getValueAt(r,2);
      String val = rteList_.getSelectedValue() + "_" + table_.getModel().getValueAt(r, 0) + "_" + table_.getModel().getValueAt(r, 1);
      ave.setProperty("id", val);
      av_.fireEvent(ave);
    }

    if (e.getSource() == setStartBtn_) {
      setOtherButtons(setStartBtn_, !setStartBtn_.isSelected());
      ACEvent ave = new ACEvent(EventTypes.RTESHP_STARTNODE);
      ave.setProperty("aborting", !setStartBtn_.isSelected());
      av_.fireEvent(ave);
    }

    if (e.getSource() == setEndBtn_) {
      setOtherButtons(setEndBtn_, !setEndBtn_.isSelected());
      ACEvent ave = new ACEvent(EventTypes.RTESHP_ENDNODE);
      ave.setProperty("aborting", !setEndBtn_.isSelected());
      av_.fireEvent(ave);
    }

    if (e.getSource() == editLinksBtn_) {
      setOtherButtons(editLinksBtn_, !editLinksBtn_.isSelected());
      ACEvent ave = new ACEvent(EventTypes.RTESHP_EDIT_LINKS);
      ave.setProperty("ending", !editLinksBtn_.isSelected());
      av_.fireEvent(ave);
    }

    if (e.getSource() == setPathBtn_) {
      setOtherButtons(setPathBtn_, !setPathBtn_.isSelected());
      ACEvent ave = new ACEvent(EventTypes.RTESHP_SPECIFY_PATH);
      ave.setProperty("ending", !setPathBtn_.isSelected());
      av_.fireEvent(ave);
    }

    if (e.getSource() == clearBtn_) {
      av_.fireEvent(new ACEvent(EventTypes.RTESHP_CLEAR_CURRENT));
    }
    if (e.getSource() == applyBtn_) {
      av_.fireEvent(new ACEvent(EventTypes.RTESHP_APPLY_CURRENT));
    }
  }

  private void routeRowSelected() {
    System.out.println("gSI " + rteList_.getSelectedIndex());
    updateTable(rteList_.getSelectedValue().toString());
  }

  private void rowSelected(int r) {
    if (autoShow_.isSelected()) {
      ACEvent ave = new ACEvent(EventTypes.RTESHP_SHOW_ITEM);
      String val = rteList_.getSelectedValue() + "_" + table_.getModel().getValueAt(r, 0) + "_" + table_.getModel().getValueAt(r, 1);
      //String val = table_.getModel().getValueAt(r,0)+"_"+table_.getModel().getValueAt(r,1)+"_"+table_.getModel().getValueAt(r,2);
      ave.setProperty("id", val);
      av_.fireEvent(ave);
    }
  }

  public void setData(String[][] data) {
    SortedSet<Integer> numRteIDs = new TreeSet<Integer>();
    SortedSet<String> strRteIDs = new TreeSet<String>();

    String[] colNames = new String[2];
    //colNames[0] = "Route ID";
    colNames[0] = "Direction";
    colNames[1] = "Pattern";
    //colNames[3] = "Resolved?";


    String[][] table = new String[data.length][2];
    for (int r = 0; r < data.length; r++) {
      String id = data[r][0];
      try {
        int num = Integer.parseInt(id);
        if (!numRteIDs.contains(num)) {
          numRteIDs.add(num);
        }
      } catch (NumberFormatException ex) {
        if (!strRteIDs.contains(id)) {
          strRteIDs.add(id);
        }
      }

      List<ImportSubInfo> subs;
      if (rteLookup_.containsKey(id)) {
        subs = rteLookup_.get(id);
      } else {
        subs = new LinkedList<ImportSubInfo>();
        rteLookup_.put(id, subs);
      }

      ImportSubInfo info = new ImportSubInfo(data[r][1], data[r][2], r);
      subs.add(info);

      //table[r][0] = id; 
      table[r][0] = data[r][1];
      table[r][1] = data[r][2];
    //table[r][3] = "No";
    }

    Iterator<Integer> numIDs = numRteIDs.iterator();
    while (numIDs.hasNext()) {
      rListModel_.addElement(numIDs.next());
    }
    Iterator<String> strIDs = strRteIDs.iterator();
    while (strIDs.hasNext()) {
      rListModel_.addElement(strIDs.next());
    }

  /*DefaultTableModel model = new DefaultTableModel(table, colNames);
  table_.setModel(model);
  table_.setRowSorter(new TableRowSorter(model));*/
  }

  private void updateTable(String id) {
    System.out.println("id: " + id);
    List<ImportSubInfo> subs = rteLookup_.get(id);

    String[] colNames = new String[2];
    colNames[0] = "Direction";
    colNames[1] = "Pattern";

    String[][] table = new String[subs.size()][2];
    Iterator<ImportSubInfo> iter = subs.iterator();
    int r = 0;
    while (iter.hasNext()) {
      ImportSubInfo info = iter.next();
      table[r][0] = info.dir_;
      table[r][1] = info.pattern_;
      r++;
    }

    DefaultTableModel model = new DefaultTableModel(table, colNames);
    table_.setModel(model);

  }

  public void resetStartNodeButton() {
    setStartBtn_.setSelected(false);
    setOtherButtons(setStartBtn_, true);
  }

  public void resetEndNodeButton() {
    setEndBtn_.setSelected(false);
    setOtherButtons(setEndBtn_, true);
  }

  public void resetSetPathButton() {
    setPathBtn_.setSelected(false);
    setOtherButtons(setPathBtn_, true);
  }

  private void setOtherButtons(AbstractButton exclude, boolean status) {
    Iterator<AbstractButton> btns = btnSet_.iterator();
    while (btns.hasNext()) {
      AbstractButton btn = btns.next();
      if (btn != exclude) {
        btn.setEnabled(status);
      }
    }
  }

  private class ImportSubInfo {

    public String dir_;
    public String pattern_;
    public int index_;

    public ImportSubInfo(String dir, String pattern, int index) {
      dir_ = dir;
      pattern_ = pattern;
      index_ = index;
    }
  }
}
